import { ConfigService } from '@nestjs/config'
import {
  Controller,
  Post,
  UploadedFile,
  UseInterceptors,
  UseGuards,
  Req,
  UnsupportedMediaTypeException,
  Delete,
  Query,
} from '@nestjs/common'
import { AuthGuard } from '@nestjs/passport'
import { FileInterceptor } from '@nestjs/platform-express'
import { Express, Request } from 'express'
// import { promisify } from 'util'
import { readdirSync, unlinkSync } from 'fs'
import { join } from 'path'
@Controller('upload')
export class UploadController {
  constructor(private readonly configServer: ConfigService) {}

  //图片上传
  @Post('image')
  @UseGuards(AuthGuard('jwt')) //验证token
  @UseInterceptors(
    FileInterceptor('image', {
      //过滤 不是图片的文件报错
      fileFilter(req: any, file: Express.Multer.File, callback) {
        if (file.mimetype.includes('image')) {
          callback(null, true)
        } else {
          callback(new UnsupportedMediaTypeException('文件类型错误'), false)
        }
      },
    }),
  )
  async uploadImage(@UploadedFile() file: Express.Multer.File, @Req() req: Request) {
    const url = this.configServer.get('HOST_URL') + '/' + file.destination + '/' + file.filename
    const userInfo = req.user
    return {
      data: {
        filename: file.filename,
        url,
        userInfo,
      },
      code: 200,
      message: '上传成功',
    }
  }

  /* 删除图片文件 */
  @Delete('deleteImg')
  @UseGuards(AuthGuard('jwt'))
  async deleteImg(@Query() info: { fileName: string }) {
    const url = join(__dirname, '../../uploads')

    const fileList = readdirSync(url)

    const index = fileList.findIndex((file) => file === info.fileName)

    if (!fileList[index]) {
      return {
        code: 404,
        message: '该图片不存在',
      }
    } else {
      const newUrl = join(url, fileList[index])
      unlinkSync(newUrl)
      return {
        code: 200,
        message: `${fileList[index]}-文件删除成功`,
      }
    }
  }
}
